library(tidyverse)
library(jpeg)
library(reshape2)

A few convenience functions

avCol <- function(xleft, ybottom, xright, ytop){
  
  df %>% 
    filter(x >= xleft, x <= xright, y>=ybottom, y<=ytop) %>% 
    summarise(red=mean(red, na.rm=T),
              green=mean(green, na.rm=T),
              blue=mean(blue, na.rm=T)) %>% 
    pmap_chr(rgb)
  
}

plotAreas <- function(xleft, ybottom, xright, ytop, av_colour, ...){
  rect(xleft, ybottom, xright, ytop, col=av_colour, ...)
}

pPal <- function(hex, ...) barplot(rep(1, length(hex)), col=hex, names=hex, las=2, border=NA, axes=F, ...)
albums <- list.files("album_covers") %>% gsub(pattern=".jpg", replacement="", x=.)

for (j in seq_along(albums)){
# Read image
i <- readJPEG(paste0("album_covers/", albums[j], ".jpg"))

# Store dimensions  
dim_x <- dim(i)[1]
dim_y <- dim(i)[2]
  
# Return 'friendly' image dataframe
df <-
  melt(i) %>% 
  spread(Var3, value) %>% 
  rename(red="1", green="2", blue="3") %>% 
  mutate(Var1 = -Var1 + dim_y) %>%
  rename(x=Var2, y=Var1) %>%
  mutate(hex = pmap_chr(list(red, green, blue), rgb),
         grey_number = pmap_dbl(list(red, green, blue), ~(..1+..2+..3)/3)) %>% 
  select(x, y, red, green, blue, hex, grey_number)

# Create a greyscale
mygreys <- colorRampPalette(c('black','white'))

# Add greyscale hex values
nlevels <- length(unique(df$grey_number))
df <- 
  df %>% 
  mutate(grey_hex = 
           mygreys(nlevels)[cut(df$grey_number, nlevels)])

# Read imajeJ selection coordinates and adjust to 'friendly' format
imj <- 
  read_csv(paste0("imageJ_selections/", albums[j], ".csv")) %>% 
  mutate(xleft = BX,
         ytop = -BY + dim_y,
         xright = xleft + Width,
         ybottom = ytop - Height)

imj <-
  imj %>% 
  mutate(av_colour = pmap_chr(list(xleft, ybottom, xright, ytop), avCol))


# Plot image and selections
par(mfrow=c(1,4), mar=c(1,1,2,1))
plot(df$x, df$y, col=df$hex, pch=".", asp=1, axes=F, xlab="", ylab="", main="Original")

plot(df$x, df$y, col=df$grey_hex, pch=".", asp=1, axes=F, xlab="", ylab="", main="Greyscale Selections")
invisible(pmap(select(imj, xleft, ybottom, xright, ytop), rect, border=6, lwd=2))

plot(df$x, df$y, col=df$hex, pch=".", asp=1, axes=F, xlab="", ylab="", type="n", main="Average colour")
invisible(pmap(select(imj, xleft, ybottom, xright, ytop, av_colour), plotAreas, border=NA))

par(mar=c(6,1,2,1))
pPal(imj$av_colour, main="Palette")

print(imj$av_colour)
}

## [1] "#E0292D" "#000000" "#E0AE5B"

## [1] "#BBBABF" "#24201F" "#6C6A6E" "#E7E6EA"

## [1] "#7E96AF" "#36641A" "#E8330B" "#232868" "#F66603" "#F88C05" "#141A0D"

## [1] "#F3EA56" "#4D84C0" "#E46A38" "#46AE52" "#DFB333" "#D5282F" "#A3D4DF"
## [8] "#070406"

## [1] "#DBD6BF" "#070403" "#47140D" "#A7A6A2" "#567698"

## [1] "#E3B92F" "#332928" "#48702C" "#AAAAAD" "#E36551"

## [1] "#BCD5E8" "#A0B1C6" "#2451B0" "#F6F7FA"

## [1] "#E7CC4A" "#100604" "#E3E7DE" "#1F0155"

## [1] "#040001" "#E9160E" "#F4D985"